package com.niuwa.p2p.action;
import java.io.File;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.core.constant.FileSystemEnum;
import com.niuwa.p2p.service.filesystem.FileSystem;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * 多文件上传
 * 
 * @author jishengjun
 * 如果office文件上传错误，可放宽到如下条件，再在逻辑里判断后缀名
 * application/octet-stream ： .dll,.a,.bin,.exe,.so
 * application/x-zip-compressed： zip
 */
@ParentPackage(value="json-default")
@InterceptorRefs(value = { 
		@InterceptorRef(value="fileUpload",params={"allowedTypes","image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/tif,image/tiff,text/xml,text/plain,"
				+ "application/vnd.ms-excel,application/excel,application/msword,"
				+ "application/vnd.ms-powerpoint,application/pdf,"  
				+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document," 
                + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,"
                + "application/vnd.openxmlformats-officedocument.presentationml.presentation,application/octet-stream,application/x-zip-compressed","maximumSize","10485760"}),
		@InterceptorRef(value = "defaultStack")		
})
public class AjaxFileMultiUploadAction extends ActionSupport{    
    /**
	 * 
	 */
	private static final long serialVersionUID = -3264533716348991025L;		
	private static final String[] ImageTypes={"image/bmp","image/png","image/gif","image/jpeg","image/psd","image/jpg","image/tif","image/tiff"};
	/** 日志 */
	private static Logger logger = Logger.getLogger(AjaxFileMultiUploadAction.class);
	//上传的文件
	private List<File> file;
	
	//文件名称
    private List<String> fileFileName;
    
    //文件类型
    private List<String> fileContentType;   

	// 文件ID
    private List<String> fileID;
    
	// 文件系统
	@Autowired
	private FileSystem fileSystem;    
	
	private String waterMarkFlag;//水印标志 image--图片水印  text--text水印
	
	private String waterText;//水印文本内容
	public List<String> getFileID() {
		return fileID;
	}

	public void setFileID(List<String> fileID) {
		this.fileID = fileID;
	}

	@JSON(serialize=false)
	public List<File> getFile() {
		return file;
	}

	public void setFile(List<File> file) {
		this.file = file;
	}

	public List<String> getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	public List<String> getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}

	private boolean success;
    
    public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	private String message = "你已成功上传文件";
    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
    @Action(value="ajaxFileMultiUpload", 
	results={@Result(type="json", name="success", params={"contentType", "text/html"}), 
  			@Result(type="json", name="input", params={"contentType", "text/html"}), 
			@Result(type="json", name="error", params={"contentType", "text/html"})})
    public String ajaxFileMultiUpload() throws Exception {
    	
    	
    	// 判断是否是空文件
    	if (file == null || file.size() == 0) {
    		success =false;
    		message = "不能上传空文件";
	       	return ERROR;
    	}
    	
    	// 判断是否是空文件
    	for(int index=0; index < file.size(); index++){
        	if (file.get(index) == null || file.get(index).length() <=0) {
        		success =false;
        		message = "文件:" + fileFileName.get(index) + "为空,不能上传空文件";
    	       	return ERROR;
        	}
    	}
    	
    	Set<String> set = new HashSet<String>();
    	// 判断文件是否重名      
    	for(String fn : fileFileName){    	 	
        	if (!set.add(fn)) {
        		success =false;
        		message = "文件:" + fn + "重复,请不要重复上传相同文件";
    	       	return ERROR;
        	}
    	}

        try {
        	for(int index=0; index < file.size(); index++){
	    		File reNameFile = new File (file.get(index).getParent(),fileFileName.get(index));
	        	FileUtils.copyFile(file.get(index), reNameFile);
		        String storefileID = saveDifferentFile(reNameFile,index);
		        if(fileID == null) {
		        	fileID = new ArrayList<String>();
		        }
		        fileID.add(storefileID);
		        reNameFile.delete();
        	}
        } catch(Exception ioe) {
         logger.info("uploadImage action execute failture:  "+ioe);
       	 success = false;
       	 message = "对不起,文件上传失败了!!!!";
       	 return ERROR;
       }
       success = true;
       return SUCCESS;
    }
    
    /** 
     * 从服务器上 删除文件 
     * @param fileName 文件名 
     * @return true: 从服务器上删除成功   false:否则失败 
     */
    @Action(value="delFiles", 
        	results={@Result(type="json", name="success"),         			 
        			 @Result(type="json", name="error")})
    public String delFiles(){  
    	
        try {        	
	        for(String fid : fileID){
	        	fileSystem.deleteFile(fid);
	        }
        } catch(Exception ioe) {
	        success =false;
	       	message = "对不起,删除文件失败";
	       	return ERROR;
        }
        
        success = true;
        message = "成功删除所有文件";
        return SUCCESS;
  
    }  
    
    @Override  
    public void addActionError(String anErrorMessage) {  
        if (anErrorMessage.startsWith("Request exceeded allowed size limit!")) { 
        	// 处理上传文件过大导致系统错误（实质：防止恶意上传）
            success =false;
            message = anErrorMessage;
            super.addActionError(anErrorMessage);
        } else {
        	// 按原来的方法处理  
            super.addActionError(anErrorMessage);
        }  
    }
    
    @Override
    public void addFieldError(String fieldName, String errorMessage) { 
    	 if (errorMessage.startsWith("上传文件 ")) { 
    		 // 处理拦截器文件过大
             success =false;
             message = errorMessage;
             super.addFieldError(fieldName, errorMessage); 
         } else if (errorMessage.startsWith("不支持上传的类型")) {
        	 // 处理拦截器上传类型不支持
             success =false;
             message = errorMessage;
             super.addFieldError(fieldName, errorMessage); 
         } else {
        	 // 按原来的方法处理  
        	 super.addFieldError(fieldName, errorMessage); 
         }
    }
    //根据不同要求保存不同文件
    public String saveDifferentFile(File reNameFile,int index) throws Exception{
    	String storefileID=null;
    	for (int i = 0; i < ImageTypes.length; i++) {
    		if(ImageTypes[i].equals(fileContentType.get(index))){
    			if("image".equals(waterMarkFlag)){
    				storefileID = fileSystem.saveImageWatermark(FileSystemEnum.PUBLIC, reNameFile);
    			}else if("text".equals(waterMarkFlag)){
    				//目前图片暂时不支持文字水印都才用图片水印 modify by tennyqin
    				storefileID = fileSystem.saveImageWatermark(FileSystemEnum.PUBLIC, reNameFile);
    			}else{
    				storefileID = fileSystem.saveImageFile(FileSystemEnum.PUBLIC,reNameFile);
    			}
        	}
		}
    	if(storefileID==null){
        	storefileID = fileSystem.savePrivateFile(reNameFile);
    	}
    	return storefileID;
    }

	public String getWaterText() {
		return waterText;
	}

	public void setWaterText(String waterText) {
		this.waterText = waterText;
	}

	
}